package com.coinland.study.window;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.os.Build;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;


/**
 * 类描述:  自定义控件
 * 创建人:  shenZ
 * 创建时间: 2020/4/16
 * 联系方式: 252079249@qq.com
 * 修改时间: 2020/4/16
 */
public class CustomView extends View {

    private String TAG = CustomView.class.getSimpleName();
    // 图片资源
    private int[] resouces = null;

    private Paint mPaintCircle;      //画圆形图像的笔
    private Paint mPaintCircleXx;      //画圆形图像背景的笔
    private Paint mPaintBorder;          //画圆形边界的笔
    private Paint mPaintBackgroud;      //画背景颜色的笔
    private int mCircleBorderWidth = 4; //边界宽度
    private int mCirlcleBorderColor = 0xFFD3623E; //边界边框颜色 (默认：姜黄)
    private int mCircleBackgroudColor = 0xFFDBDBDB; //圆形头像背景色

    public CustomView(Context context) {
        super(context);
        init();
        Log.e(TAG, "调用构造方法1");
    }

    public CustomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
        Log.e(TAG, "调用构造方法2");
    }

    public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
        Log.e(TAG, "调用构造方法3");
    }


    private void init() {
        mPaintCircle = new Paint();
        mPaintCircle.setAntiAlias(true);//抗锯齿,没有消除锯齿的话，图片变换会很难看的，因为有些像素点会失真
        mPaintCircle.setColor(Color.parseColor("#FFFFFF"));  // 设置为白色
        mPaintCircle.setStyle(Paint.Style.FILL);

        mPaintCircleXx = new Paint();
        mPaintCircleXx.setAntiAlias(true);
        mPaintCircleXx.setColor(Color.parseColor("#FFFFFF"));  // 设置为白色
        mPaintCircleXx.setStyle(Paint.Style.FILL);

        //给图形加边框
        mPaintBorder = new Paint();
        mPaintBorder.setAntiAlias(true);
        mPaintBorder.setTextSize(mCircleBorderWidth);
        mPaintBorder.setStyle(Paint.Style.STROKE);
        mPaintBorder.setStrokeWidth(mCircleBorderWidth);
        mPaintBorder.setColor(mCirlcleBorderColor);
        //设定是否使用图像抖动处理，会使绘制出来的图片颜色更加平滑和饱满，图像更加清晰
        mPaintBorder.setDither(true);

        //画背景颜色的笔
        mPaintBackgroud = new Paint();
        mPaintBackgroud.setColor(mCircleBackgroudColor);
        mPaintBackgroud.setAntiAlias(true);
        mPaintBackgroud.setStyle(Paint.Style.FILL);
    }


    private final float SCALE = 0.75f;
    private float[] Second_XY = new float[2];

    /**
     * 视图绘制工作
     *
     * @param canvas
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    @Override
    protected void onDraw(Canvas canvas) {
        if (resouces != null && resouces.length > 0) {
            int width = getMeasuredWidth();
            int height = getMeasuredHeight();
            // 绘制控件背景
            int mViewSize = Math.min(width, height);
            //圆的半径短的二分之一作为半径
            float centerX = mViewSize / 2;
            float centerY = mViewSize / 2;
            canvas.drawCircle(centerX, centerY, mViewSize / 2, mPaintBackgroud);

            int length = resouces.length;
            float radius = SCALE * mViewSize / 2;
            if (length == 1) {
                // 缩放后的bitmap
                Bitmap target = scaleBitmap(resouces[0], radius, new float[]{centerX, centerY});
                canvas.drawCircle(centerX, centerY, radius, mPaintCircleXx);
                //画图片
                canvas.drawBitmap(target, Left_Top[0], Left_Top[1], mPaintCircle);
                //画边框
                canvas.drawCircle(centerX, centerY, radius + mCircleBorderWidth / 2, mPaintBorder);

            } else if (length == 2) {
                float angle = 360 / length;
                float chilRadius = radius / 2;  // 设置子圆的半径
                for (int i = 0; i < length; i++) {
                    float finalAngle = i * angle + 180;
                    double radian = Math.toRadians(finalAngle);
                    float x = (float) (centerX + Math.cos(radian) * chilRadius * 0.9f);
                    Bitmap target = scaleBitmap(resouces[i], chilRadius, new float[]{x, centerY});
                    canvas.drawCircle(x, centerY,  chilRadius, mPaintCircleXx);
                    //画图片
                    canvas.drawBitmap(target, Left_Top[0], Left_Top[1], mPaintCircle);
                    // 画边框
                    canvas.drawCircle(x, centerY, chilRadius + mCircleBorderWidth / 2, mPaintBorder);
                }
            } else {
                float angle = 360 / length;
                float chilRadius = radius / 2;  // 设置子圆的半径

                for (int i = 0; i < length; i++) {
                    // 第一个圆先不画，  最后画
                    if (i == 0) continue;

                    float finalAngle = i * angle + 180;
                    double radian = Math.toRadians(finalAngle);
                    float x = (float) (centerX + Math.cos(radian) * chilRadius);
                    float y = (float) (centerY + Math.sin(radian) * chilRadius);

                    Bitmap target = scaleBitmap(resouces[i], chilRadius, new float[]{x, y});
                    canvas.drawCircle(x, y, chilRadius, mPaintCircleXx);
                    //画图片
                    canvas.drawBitmap(target, Left_Top[0], Left_Top[1], mPaintCircle);

                    // 记录第二个圆的 圆心
                    if (i == 1) {
                        Second_XY[0] = x;
                        Second_XY[1] = y;
                    }
                }

                //处理最后一个圆，遮挡第一个圆的部分,最后一个圆使用path画
                Path path1 = new Path();
                path1.addCircle(centerX - chilRadius, centerY, chilRadius, Path.Direction.CW);
                Path path2 = new Path();
                path2.addCircle(Second_XY[0]
                        , Second_XY[1], chilRadius, Path.Direction.CW);
                path1.op(path2, Path.Op.DIFFERENCE);//从第一条路径中减去第二条路径
                canvas.drawPath(path1, mPaintCircleXx);

                Bitmap bitmap = scaleBitmap(resouces[0], chilRadius, new float[]{centerX - chilRadius, centerY});
                Bitmap target = Bitmap.createBitmap((int) (2 * chilRadius), (int) (2 * chilRadius),
                        Bitmap.Config.ARGB_8888);
                Canvas canvasX = new Canvas(target);

                // 画路径
                Path path1x = new Path();
                path1x.addCircle(chilRadius, chilRadius, chilRadius, Path.Direction.CW);
                Path path2x = new Path();
                path2x.addCircle(Second_XY[0] - centerX + 2 * chilRadius
                        , Second_XY[1] - centerY + chilRadius, chilRadius, Path.Direction.CW);
                path1x.op(path2x, Path.Op.DIFFERENCE);//从第一条路径中减去第二条路径

                canvasX.drawPath(path1x, mPaintCircle);
                mPaintCircle.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
                // 关键代码，关于Xfermode和SRC_IN请自行查阅
                canvasX.drawBitmap(bitmap, Math.round(tanXY),
                        Math.round(tanXY), mPaintCircle);
                //去除Xfermode
                mPaintCircle.setXfermode(null);
                canvas.drawBitmap(target, centerX - 2 * chilRadius, centerY - chilRadius, mPaintCircle);

                // 给所有圆画边框
                for (int i = 0; i < length; i++) {
                    float finalAngle = i * angle + 180;
                    double radian = Math.toRadians(finalAngle);
                    float x = (float) (centerX + Math.cos(radian) * chilRadius);
                    float y = (float) (centerY + Math.sin(radian) * chilRadius);

                    //画边框
                    Path borderPaths = new Path();
                    RectF rectF = new RectF(x - chilRadius, y - chilRadius,
                            x + chilRadius, y + chilRadius);
                    float startAngle = i * angle;
                    borderPaths.addArc(rectF, startAngle, 180 + angle);
                    canvas.drawPath(borderPaths, mPaintBorder);
                }
            }
        } else {
            super.onDraw(canvas);
        }

    }


    private float[] Left_Top = new float[2];
    private float bitScale = 0.8f;
    private double tanXY = 0;

    /**
     * 使用BitmapShader画圆图形
     */
    private Bitmap scaleBitmap(int resouce, float radius, float[] center) {
        //最终bitmap的宽度
        double targetWidth = Math.sqrt(2) * radius;
        // 生成bitmap
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resouce);
        int bw = bitmap.getWidth();
        int bh = bitmap.getHeight();
        int min = Math.min(bw, bh);
        // 缩放倍数
        float scale = (float) (bitScale * targetWidth / min);
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);// 使用后乘

        Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bw, bh, matrix, false);
        if (!bitmap.isRecycled()) {
            bitmap.recycle();
        }

        float xy = (float) (bitScale * Math.sqrt(2) * radius / 2);
        tanXY = (1 - bitScale * Math.sqrt(2) / 2) * radius;
        Left_Top[0] = center[0] - xy;
        Left_Top[1] = center[1] - xy;
        return newBitmap;
    }

    /**
     * 获取控件的宽和高度  (在控件大小发生改变时调用)
     *
     * @param w
     * @param h
     * @param oldw
     * @param oldh
     */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

    }

    /**
     * 测量View宽高 （在View放置到父容器时调用）
     *
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }


    /**
     * 计算当前View以及子View的位置
     *
     * @param left
     * @param top
     * @param right
     * @param bottom
     */
    @Override
    public void layout(int left, int top, int right, int bottom) {
        super.layout(left, top, right, bottom);
    }


    /**
     * 去让控件重绘
     */
    @Override
    public void postInvalidate() {
        super.postInvalidate();
    }

    /**
     * 设置图像背景
     *
     * @param resouces
     */
    public void setResouces(int[] resouces) {
        this.resouces = resouces;
        postInvalidate();
    }

}
